package services

import (
	"dog-blog/app/post/models"
	"dog-blog/base/database/sqlite"
)

// SaveComment 保存一条记录
func SaveComment(comment models.Comment) bool {
	stmt, err1 := sqlite.DB.Prepare("INSERT INTO t_comment(postId, username, email, content, url) VALUES(?,?,?,?,?)")
	sqlite.CheckErr(err1)

	_, err2 := stmt.Exec(comment.PostId, comment.UserName, comment.Email, comment.Content, comment.URL)
	sqlite.CheckErr(err2)
	return true
}

// FindComments 获取文章所有的评论
func FindComments(c *models.CommentPageReq) (models.CommentPage, bool) {

	// 总记录数
	totalRecord := 0
	// 总页数
	totalPageCount := 0

	// 查询总记录数
	sql := "SELECT COUNT(*) FROM t_comment WHERE postId = ?"
	err := sqlite.DB.QueryRow(sql, c.PostId).Scan(&totalRecord)
	sqlite.CheckErr(err)

	if totalRecord == 0 {
		page := models.CommentPage{}
		page.NextPage = -1
		page.HasNextPage = false
		page.Rows = []models.Comment{}
		return page, true
	}

	// 总页数
	totalPageCount = (totalRecord + c.PageLimit - 1) / c.PageLimit

	// 分页查询记录
	sql = "SELECT id, postId, parentId, username, email, content, url, DATE(time, 'localtime') FROM t_comment WHERE postID = ? ORDER BY time DESC LIMIT (?-1) * ?, ?"
	rows, err := sqlite.DB.Query(sql, c.PostId, c.PageNum, c.PageLimit, c.PageLimit)
	sqlite.CheckErr(err)

	comments := []models.Comment{}

	for rows.Next() {
		comment := models.Comment{}
		err = rows.Scan(&comment.ID, &comment.PostId, &comment.ParentID, &comment.UserName, &comment.Email, &comment.Content, &comment.URL, &comment.Time)
		sqlite.CheckErr(err)
		comments = append(comments, comment)
	}

	page := models.CommentPage{}
	page.NextPage = c.PageNum + 1
	page.HasNextPage = !(totalPageCount == c.PageNum)
	page.Rows = comments

	return page, true
}
